package com.sharemedia.net
{
	import com.sharemedia.events.PeerEvent;
	
	import flash.events.Event;
	import flash.events.NetStatusEvent;
	import flash.net.GroupSpecifier;
	import flash.net.NetGroup;

	[Event(name="peerConnected", type="com.sharemedia.events.PeerEvent")]
	[Event(name="peerMessage", type="com.sharemedia.events.PeerEvent")]
	[Event(name="memberCountChanged", type="flash.events.Event")]
	public class GroupPeer extends BasePeer
	{
		
		protected var netGroup:NetGroup;
		
		private var _groupName:String;
		
		public function GroupPeer()
		{
			super();
		}
		
		public function init(groupName:String):void
		{
			_groupName = groupName;
			initConnection();
		}
		
		public function post(message:Object):void
		{
			netGroup.post(message);
		}
		
		protected function netStatusHandler(event:NetStatusEvent):void
		{
			logger.info(event.info.code);
			
			if(event.info.code == "NetGroup.Posting.Notify")
			{
				if(hasEventListener(PeerEvent.PEER_MESSAGE))
					dispatchEvent(new PeerEvent(PeerEvent.PEER_MESSAGE, event.info.message));
			}
			
			if(event.info.code == "NetGroup.Neighbor.Connect")
			{
				_memberCount++;
				dispatchEvent(new Event("memberCountChanged"));
			}
			
			if(event.info.code == "NetGroup.Neighbor.Disconnect")
			{
				_memberCount--;
				dispatchEvent(new Event("memberCountChanged"));
			}
		}
		
		private var _memberCount:Number=0;
		
		[Bindable("memberCountChanged")]
		public function get memberCount():Number
		{
			return _memberCount;
		}
		
		override protected function setupStream():void
		{
			var groupSpec:GroupSpecifier = new GroupSpecifier(_groupName);
			groupSpec.serverChannelEnabled = true;
			groupSpec.multicastEnabled = true;
			groupSpec.postingEnabled = true;
			
			if(netGroup)
				netGroup.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);	
				
			netGroup = new NetGroup(netConnection, groupSpec.groupspecWithAuthorizations());
			netGroup.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);	
			
			dispatchEvent(new PeerEvent(PeerEvent.PEER_CONNECTED));
		}
	}
}